/**
 * 基于TCP传输层协议实现一个websocket应用服务器
 */

const net = require('net')
const {EventEmitter} = require('events');
const {toHeaders, toAcceptKey, unmask} = require('./utils.js')

// EventEmitter事件库， 可以用来发布和订阅事件  进行事件监听  jquery on trigger  addEventListener

class Server extends EventEmitter {
    constructor(options) {
        super(options);
        this.options = options;
        // 创建一个TCP服务器  每当服务器收到客户端连接后
        this.server = net.createServer(this.listener)
        this.server.listen(options.port || 8888)
    }

    // socket 套接字  用它来发送和接收信息
    listener = (socket) => {
        socket.setKeepAlive(true)       // 保持长连接
        // 当服务器收到客户端发过来的data后  chunk就是客户端发给服务器的数据
        socket.on('data', (chunk) => {
            if (chunk.toString().match(/Upgrade: websocket/)) {
                //Upgrade: websocket
                this.upgradeProtocol(socket, chunk.toString())
            }
        })

        // 触发connection事件， 并传递socket对象
        this.emit('connection', socket)
    }
    upgradeProtocol = (socket, chunk) => {
        let rows = chunk.split('\r\n');

        let headers = toHeaders(rows.slice(1, -2));  // 第一行和后面两行不要
        let wsKey = headers['Sec-WebSocket-Key']
        let acceptKey = toAcceptKey(wsKey);
        console.log(acceptKey);
        let response = [
            'HTTP/1.1 101 Switching Protocols',
            'Upgrade: websocket',
            'Connection: Upgrade',
            `Sec-WebSocket-Accept: ${acceptKey}`,
            '\r\n'
        ].join('\r\n');
        socket.write(response);

    }
}



exports.Server = Server;